package com.lujieni.springbootmybatis.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.extra.spring.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataDesensitizationUtil {

    private static final Logger log = LoggerFactory.getLogger(DataDesensitizationUtil.class);
    private static final String ENCRYPTOR_PROPERTY_NAME = "mybatis-plus.encryptor.password";
    private static AES aes;

    static {
        String password = SpringUtil.getProperty(ENCRYPTOR_PROPERTY_NAME);
        Assert.notEmpty(password, "配置项({}) 不能为空", new Object[]{ENCRYPTOR_PROPERTY_NAME});
        aes = SecureUtil.aes(password.getBytes());
    }

    public static String encrypt(String rawValue) {
        try {
            return rawValue == null ? null : getEncryptor().encryptBase64(rawValue);
        } catch (Exception var2) {
            Exception e = var2;
            log.error("ERROR method EncryptTypeHandler.encrypt : {} ", e.getLocalizedMessage());
            return rawValue;
        }
    }

    /**
     * 如果无法成为Bean，确保SpringUtil已初始化
     * @return
     */
    private static AES getEncryptor() {
        return aes;
    }

}
